import React, { Component } from 'react';
import myaxios from "../../utils/myaxios";
import { NavBar, Icon, Carousel, Toast } from "antd-mobile";
import "./GoodDetail.scss"
export default class GoodDetail extends Component {
  // constructor(props) {
  //   super(props);
  //   console.log(props);
  // }
  state = {
    goodInfo: {},
    imgHeight: 250,//轮播图默认高度
    showSwiper: false, // 设置轮播图显示状态默认不显示
    showCollect: false,//收藏状态显示
  }
  componentDidMount() {
    let { goods_id } = this.props.match.params;//  解构赋值写法<=>let goods_id  = this.props.match.params.goods_id ;
    myaxios
      .get("goods/detail", {
        params: {
          goods_id,
        }
      })
      .then(res => {
        // console.log(res);
        //  3.轮播图请求回来
        this.setState({
          goodInfo: res,
          showSwiper: true,
        })
      })
      .catch(err => console.log(err));
    // 初次进入商品详情的时候判断商品是否被收藏
    let collection_str = localStorage.getItem("collections");
    let collections = JSON.parse(collection_str || "[]");
    // 对收藏进行循环遍历 判断是否在收藏中
    let index = collections.findIndex(v => {
      if (v.goods_id === parseInt(goods_id)) {
        return true;
      }
      return v.goods_id //为何一定要返回一个value
    })
    if (index !== -1) {
      this.setState({
        showCollect: true
      })
    }

  }
  // 收藏的功能
  handleCollect = (params) => {
    // collections 代表的收藏的数据数组
    let collection_str = localStorage.getItem("collections");
    let collections = JSON.parse(collection_str || "[]");
    // 对收藏进行循环遍历 判断是否在收藏中
    let index = collections.findIndex(v => {
      if (v.goods_id === this.state.goodInfo.goods_id) {
        return true;
      }
      return v.goods_id //为何一定要返回一个value
    })
    if (index !== -1) {
      // 代表已经收藏
      collections.splice(index, 1);
      Toast.info("收藏已取消", 1);
      this.setState({
        showCollect: false
      })
    } else {
      Toast.info("收藏成功", 1);
      collections.push(this.state.goodInfo);
      this.setState({
        showCollect: true
      })
    }
    localStorage.setItem("collections", JSON.stringify(collections));
  }
  // 跳转到购物车
  gotoCart = (params) => {
    this.props.history.push("/cart")
  }
  // 跳转到支付页面
  pay = (params) => {
    this.props.history.push("/pay")
  }
  // 加入购物车
  addToCart = (params) => {
    // 1.从本地缓存获取购物车数据
    let cart_str = localStorage.getItem("carts");
    let carts = JSON.parse(cart_str || "[]");
    console.log(carts);
   
    let { goods_id } = this.props.match.params;
    console.log(goods_id , parseInt(goods_id));
    let index = carts.findIndex(v => {
      if (v.goods_id === parseInt(goods_id)) {
       
        return true;
      }
      return v.goods_id //为何一定要返回一个value
    })
    console.log(index);
    if (index === -1) {
      let goods_info = this.state.goodInfo;
      goods_info.num = 1; //首次添加商品
      goods_info.checked = true; //购物车中商品默认选中
      carts.push(goods_info);
    } else {
      carts[index].num++; //第n次添加商品 n>1
    }
    Toast.info("加入购物车成功", 1);
    localStorage.setItem("carts", JSON.stringify(carts));
  }

  render() {
    return (
      <div className="yg-detail">
        <NavBar
          className="yg-detail-nav"
          mode="light"
          icon={<Icon type="left" />}
          onLeftClick={() => window.history.go(-1)}
        >
          商品详情
        </NavBar>
        {/* 首页轮播图 */}
        <div className="yg-detail-swiper">
          {/* 2. showSwiper和轮播图绑定 */}
          {this.state.showSwiper && (
            <Carousel
              autoplay={true}
              infinite
            >
              {this.state.goodInfo.pics && this.state.goodInfo.pics.map(v => {
                return (
                  <div
                    key={v.goods_id}
                    className="imageWrapper"
                    style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                  >
                    <img
                      src={v.pics_mid}
                      alt=""
                      style={{ width: '100%', verticalAlign: 'top' }}
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event('resize'));
                        this.setState({ imgHeight: 'auto' });
                      }}
                    />
                  </div>
                );
              })}
            </Carousel>
          )}
        </div>
        {/* 价格和分享区域 */}
        <div className="yg-detail-price">
          <div className="price-left">
            <span className="title1">￥{this.state.goodInfo.goods_price}</span>
          </div>
          <div className="price-right">
            <i className="iconfont icon-fenxiang"></i>
            <i className={this.state.showCollect ? "iconfont icon-shoucang1 active" : "iconfont icon-shoucang1 unactive"} onClick={this.handleCollect}></i>
          </div>
        </div>
        {/* 商品标题 */}
        <div className="yg-detail-title">
          {this.state.goodInfo.goods_name}
        </div>
        {/* 图文详情 */}
        <div className="yg-deatil-richtext">
          <div className="richtext-title">图文详情</div>
          <div className="richtext-content" dangerouslySetInnerHTML={{ __html: this.state.goodInfo.goods_introduce }}>
          </div>
        </div>
        {/* 底部工具栏 */}
        <div className="yg-detail-bottom">
          <div className="bottom-content">
            <i className="iconfont icon-kefu"></i>
            <div className="title">联系客服</div>
          </div>
          <div className="bottom-cart" onClick={this.gotoCart}>
            <i className="iconfont icon-gwc-copy"></i>
            <div className="title">购物车</div>
          </div>
          <div className="bottom-addToCart" onClick={this.addToCart}>
            <span className="title1">加入购物车</span>
          </div>
          <div className="bottom-buy" onClick={this.pay}>
            <span className="title2">立即购买</span>
          </div>
        </div>
      </div>
    )
  }
}
